﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TopVidionApplication;
using TopVisionVideoStream;
using VideoStream.Common;
using VideoStream.CustomControl;
using VideoStream.Model;
using VideoStream.Properties;
using System.Linq;

namespace VideoStream.Windows
{
    public partial class Windows_Display : VideoStream.Windows.WindowsBase
    {
        #region Filds

        private DisplayType dspType = DisplayType.OneScreen;

        private bool volumeSliderCtl = false;
        private bool rslSelectionCtl = false;
        private bool mute = false;
        private bool micmute = false;
        private bool definitionChanging = false;
        private bool voiceOnly = false;
        private bool isfull = false;
        private int preVolume;
        private string curDefinition;

        private Panel voiceOnlyMask;
        private Control preParent;

        private bool isFlash = false;
        private bool isZoom = false;
        private bool isFocus = false;
        private bool isMark = false;
        private bool isPhoto = false;
        private bool isSrcShot = false;
        private bool isSendImage = false;
        private int preZoom;
        private int zoomCount;

        private WindowsBase winDraw;
        private WindowsBase winImgDraw;

        private List<Label> txtList;

        private string glassSettingHead = "眼镜默认相机参数";
        private int brightness = 50;
        private int contrast = 50;

        #endregion


        #region Property
        public bool IsFlash => isFlash;
        public bool IsZoom => isZoom;
        public bool IsFocus => isFocus;
        public bool IsMark => isMark;
        public bool IsPhoto => isPhoto;
        public bool IsSrcShot => isSrcShot;
        public bool IsSendImage => isSendImage;

        public int RemoteHandle => (int)panel_Remote.Handle;
        public int LocalHandle => (int)panel_Local.Handle;
        public DisplayType DspType
        {
            get { return dspType; }
            set
            { dspType = value; }
        }
        public bool Mute
        {
            get { return mute; }
            set
            {
                mute = value;
                if (Mute)
                {
                    preVolume = (int)tvsolider_Volume.Value;
                    tvsolider_Volume.Value = 0;
                    //btn_Volume.Image = Resources.静音;
                    tvsolider_Volume.Visible = false;
                    TVVS.SpeakerVolume = 0;
                }
                else
                {
                    tvsolider_Volume.Visible = true;
                    tvsolider_Volume.Value = preVolume;
                    //btn_Volume.Image = Resources.音量;
                    TVVS.SpeakerVolume = preVolume;
                }
            }
        }
        public bool MicMute
        {
            get { return micmute; }
            set
            {
                micmute = value;
                TVVS.MicrophoneMute = MicMute;
            }
        }
        public bool VoiceOnly
        {
            get { return voiceOnly; }
            set
            {
                voiceOnly = value;
                TVVS.Features_VoiceOnly();
                if (voiceOnly)
                {
                    voiceOnlyMask = new Panel();
                    voiceOnlyMask.BackColor = TVColor.Color_Dark;
                    voiceOnlyMask.Parent = panel_Remote;
                    voiceOnlyMask.BringToFront();
                    voiceOnlyMask.Dock = DockStyle.Fill;
                    voiceOnlyMask.Show();
                    panel_Local.BringToFront();
                    btn_Hangup.BringToFront();
                }
                else
                {
                    if (voiceOnlyMask != null)
                    {
                        if (!voiceOnlyMask.IsDisposed)
                        {
                            panel_Remote.Controls.Remove(voiceOnlyMask);
                            voiceOnlyMask.Dispose();
                        }
                        voiceOnlyMask = null;
                    }
                    panel_Local.BringToFront();
                    btn_Hangup.BringToFront();
                }
            }
        }
        public bool IsFullScreen
        {
            get { return isfull; }
            set
            {
                isfull = value;
                SetScreenModel();
            }
        }
        public string CurDefinition
        {
            get { return curDefinition; }
            set
            {
                curDefinition = value;
                SelectDifinition(CurDefinition);
            }
        }
        public List<Label> TxtList
        {
            get
            {
                if (txtList == null) txtList = new List<Label>();
                return txtList;
            }
            set { txtList = value; }
        }


        #endregion


        public Windows_Display()
        {
            InitializeComponent();
            InitUI();
        }


        #region Override

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            InitEvent();
            UpdateUI();
            UpdateQos();
            ActiveToolWithReady();
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            Windows_Main.Instance.ShowMask(false);
            Focus();
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Enter & !txt_MessageInput.Focused) txt_MessageInput.Focus();
            if (keyData == Keys.Escape)
            {
                if (IsFullScreen) IsFullScreen = false;
            }

            return base.ProcessCmdKey(ref msg, keyData);
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            if (IsFullScreen)
            {
                e.Cancel = true;
                IsFullScreen = false;
            }

            base.OnClosing(e);
        }

        protected override void OnClosed(EventArgs e)
        {
            TVVS.MessageInfoEvent -= TVVS_MessageInfoEvent;

            base.OnClosed(e);

            //TVVS.VideoCallCancel();
            //Windows_Main.Instance.ShowVideoCallWindows();
            //Hide();
        }

        public override void InitUI()
        {
            base.InitUI();
            this.ShowInTaskbar = false;
            this.TopLevel = false;
            this.Dock = DockStyle.Fill;

            btn_LD.Tag = "240";
            btn_SD.Tag = "480";
            btn_HD.Tag = "720";
            btn_FHD.Tag = "1080";
        }

        public override void InitEvent()
        {
            base.InitEvent();

            panel_Remote.SizeChanged += Panel_Remote_SizeChanged;
            btn_Hangup.Click += Btn_Hangup_Click;

            //btn_Volume.MouseClick += Btn_Volume_MouseClick;
            btn_Volume.MouseEnter += Volume_MouseEnter;
            btn_Volume.MouseLeave += Volume_MouseLeave;
            tvsolider_Volume.CMouseEnter += Volume_MouseEnter;
            tvsolider_Volume.CMouseLeave += Volume_MouseLeave;
            tvsolider_Volume.ValueChanged += Tvsolider_Volume_ValueChanged;
            btn_Volume.Click += Btn_Volume_Click;

            // Control paint
            panel_RslSelection.Paint += Panel_RslSelection_Paint;
            panel_GlassSetting.Paint += Panel_RslSelection_Paint;

            // Resolution Difinition
            btn_Definition.Click += Btn_Definition_Click;
            foreach (Control item in panel_RslSelection.Controls)
            {
                item.Click += DefinitionMenu_Click;
            }

            // Mic Mute
            btn_MicMute.Click += Btn_MicMute_Click;

            // Voice only
            btn_VoiceOnly.Click += Btn_VoiceOnly_Click;

            // Glass Setting
            btn_GlassSetting.Click += Btn_GlassSetting_Click;
            btn_GlassBP.Click += (o, e) => { SetBrightness(10); };
            btn_GlassBD.Click += (o, e) => { SetBrightness(-10); };
            btn_GlassCP.Click += (o, e) => { SetContrast(10); };
            btn_GlassCD.Click += (o, e) => { SetContrast(-10); };

            // Send Text
            txt_MessageInput.KeyPress += Txt_MessageInput_KeyPress;
            btn_SendTxt.Click += Btn_SendTxt_Click;
            btn_ClearTxt.Click += Btn_ClearTxt_Click;

            // Screen ctl
            panel_Remote.DoubleClick += Panel_Remote_DoubleClick;
            panel_Remote.MouseDown += Panel_Remote_MouseDown;



            // Tools
            btn_Flash.Click += ToolClick;
            btn_Zoom.Click += ToolClick;
            btn_Focus.Click += ToolClick;
            btn_Mark.Click += ToolClick;
            btn_ScreenShot.Click += ToolClick;
            btn_TakePhoto.Click += ToolClick;

            tvslider_Zoom.ValueChanged += Tvslider_Zoom_ValueChanged;

            // message
            TVVS.MessageInfoEvent += TVVS_MessageInfoEvent;
        }

        private void Btn_ClearTxt_Click(object sender, EventArgs e)
        {
            ClearText();
        }

        private void Txt_MessageInput_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                SendText();
                e.Handled = true;
            }
        }

        private void Tvsolider_Volume_ValueChanged(double value)
        {
            TVVS.SpeakerVolume = (int)value;
        }

        public override void UpdateUI()
        {
            base.UpdateUI();

            panel_Remote.BackColor = Color.Black;
            panel_Local.BackColor = Color.Black;

            this.BackColor = TVColor.Color_Dark;

            HideVolumeBar();
            HideRslSelection();
            HideZoomBar();
            HideGlassSettingBar();

            btn_Hangup._Text = TVVS.CallindID;

            UpdateGlassBC();
        }

        #endregion


        #region Control Event

        private void Panel_Remote_SizeChanged(object sender, EventArgs e)
        {
            switch (DspType)
            {
                case DisplayType.OneScreen:
                    panel_Local.Visible = false;
                    btn_Hangup.Location = new Point(panel_Remote.Width - btn_Hangup.Width - 5, 5);
                    break;
                case DisplayType.TwoScreen:
                    panel_Local.Visible = true;
                    btn_Hangup.Location = new Point(panel_Remote.Width - btn_Hangup.Width - 5, 5);
                    break;
                default:
                    break;
            }

            panel_Remote.Hide();
            panel_Remote.Show();

        }

        private void Btn_Hangup_Click(object sender, EventArgs e)
        {
            Hangup();
        }

        private async void Volume_MouseLeave(object sender, EventArgs e)
        {
            volumeSliderCtl = false;
            await Task.Delay(300);
            if (!volumeSliderCtl)
                HideVolumeBar();
        }

        private void Volume_MouseEnter(object sender, EventArgs e)
        {
            volumeSliderCtl = true;
            ShowVolumeBar();
        }

        private void Btn_Volume_Click(object sender, EventArgs e)
        {
            Mute = !Mute;
        }

        private void Panel_RslSelection_Paint(object sender, PaintEventArgs e)
        {
            var panel = (Panel)sender;
            Graphics g = e.Graphics;
            Pen p = new Pen(TVColor.Color_HighLight, 1);
            g.DrawRectangle(p, 0, 0, panel.Width - p.Width, panel.Height - p.Width);
        }

        private void Btn_Definition_Click(object sender, EventArgs e)
        {
            if (rslSelectionCtl)
            {
                HideRslSelection();
            }
            else
            {
                ShowRslSelection();
            }
        }

        private void DefinitionMenu_Click(object sender, EventArgs e)
        {
            if (definitionChanging) return;
            PictureButton pb = (PictureButton)sender;
            if (pb == btn_LD) TVVS.Features_Resolution(Resolution.r240P);
            if (pb == btn_SD) TVVS.Features_Resolution(Resolution.r480P);
            if (pb == btn_HD) TVVS.Features_Resolution(Resolution.r720P);
            if (pb == btn_FHD) TVVS.Features_Resolution(Resolution.r1080P);
            HideRslSelection();
            definitionChanging = true;
            string preDf = btn_Definition._Text;
            object preTag = btn_Definition.Tag;
            DefinitionChanging(preDf, preTag, pb);
            btn_Definition.Checked = false;
        }

        private void Btn_MicMute_Click(object sender, EventArgs e)
        {
            MicMute = !MicMute;
        }

        private void Btn_VoiceOnly_Click(object sender, EventArgs e)
        {
            VoiceOnly = !VoiceOnly;
        }

        private void Btn_SendTxt_Click(object sender, EventArgs e)
        {
            SendText();
        }

        private void Panel_Remote_DoubleClick(object sender, EventArgs e)
        {
            if (IsMark || IsPhoto || IsSrcShot)
            {
                Windows_MessageBox wmb = new Windows_MessageBox(TVString.STR_IsMarkOn, MessageBoxButtons.OK, MessageBoxIcon.Information);
                wmb.ShowDialog(this);
                return;
            }
            IsFullScreen = !IsFullScreen;
        }

        private async void ToolClick(object sender, EventArgs e)
        {
            PictureButton pb = sender as PictureButton;
            if (pb != null)
            {
                pb.Enabled = false;
                if (pb == btn_Flash) DoFlash();
                if (pb == btn_Zoom) DoZoom();
                if (pb == btn_Focus) ReadyFocus();
                if (pb == btn_Mark) DoMark();
                if (pb == btn_ScreenShot) DoScreenShot();
                if (pb == btn_TakePhoto) DoTakePhoto();
                if (pb == btn_SendPicture) DoSendImage();
                await Task.Delay(500);
                pb.Enabled = true;
            }
        }

        private void Tvslider_Zoom_ValueChanged(double value)
        {
            int zoom = (int)((100 - value) / 100 * 6);
            if (zoom != preZoom)
            {
                preZoom = zoom;
                TVVS.Features_Zoom(zoom);
            }
        }

        private void Btn_GlassSetting_Click(object sender, EventArgs e)
        {
            if (btn_GlassSetting.Checked)
            {
                ShowGlassSettingBar();
            }
            else
            {
                HideGlassSettingBar();
            }
        }

        #endregion


        #region TVVS Event

        private void TVVS_MessageInfoEvent(string msg)
        {
            if (msg.StartsWith(glassSettingHead))
            {
                var args = msg.Split(',');
                brightness = int.Parse(args[1]);
                contrast = int.Parse(args[2]);
                UpdateGlassBC();
            }
        }

        #endregion


        #region Method

        public void Hangup()
        {
            Windows_Main.Instance.Hangup();
            Hide();
            Close();
        }

        private void ShowVolumeBar()
        {
            tvsolider_Volume.BringToFront();
            Point newPos = PointToClient(btn_Volume.PointToScreen(Point.Empty));
            newPos.X -= (tvsolider_Volume.Width - btn_Volume.Width) / 2;
            newPos.Y -= tvsolider_Volume.Height;
            tvsolider_Volume.Value = TVVS.SpeakerVolume;
            tvsolider_Volume.Location = newPos;
            if (!Mute)
                tvsolider_Volume.Show();
        }

        private void HideVolumeBar()
        {
            tvsolider_Volume.Hide();
        }

        private void ShowRslSelection()
        {
            if (definitionChanging) return;
            rslSelectionCtl = true;
            panel_RslSelection.BringToFront();
            Point newPos = PointToClient(btn_Definition.PointToScreen(Point.Empty));
            newPos.X -= (panel_RslSelection.Width - btn_Definition.Width) / 2;
            newPos.Y -= panel_RslSelection.Height - 5;
            panel_RslSelection.Location = newPos;
            panel_RslSelection.Show();
            panel_RslSelection.Focus();
        }

        private void HideRslSelection()
        {
            rslSelectionCtl = false;
            if (!rslSelectionCtl)
                panel_RslSelection.Hide();

        }

        private void SelectDifinition(string difinition)
        {
            btn_Definition.Tag = difinition;
            btn_LD.NormalBgColor = Color.FromArgb(40, 40, 40);
            btn_SD.NormalBgColor = Color.FromArgb(40, 40, 40);
            btn_HD.NormalBgColor = Color.FromArgb(40, 40, 40);
            btn_FHD.NormalBgColor = Color.FromArgb(40, 40, 40);

            switch (difinition)
            {
                case "240":
                    btn_LD.NormalBgColor = Color.FromArgb(2, 110, 185);
                    btn_Definition._Text = btn_LD._Text;
                    break;
                case "480":
                    btn_SD.NormalBgColor = Color.FromArgb(2, 110, 185);
                    btn_Definition._Text = btn_SD._Text;
                    break;
                case "720":
                    btn_HD.NormalBgColor = Color.FromArgb(2, 110, 185);
                    btn_Definition._Text = btn_HD._Text;
                    break;
                case "1080":
                    btn_FHD.NormalBgColor = Color.FromArgb(2, 110, 185);
                    btn_Definition._Text = btn_FHD._Text;
                    break;
                default:
                    btn_LD.NormalBgColor = Color.FromArgb(2, 110, 185);
                    btn_Definition._Text = btn_LD._Text;
                    break;
            }

        }

        private async void UpdateQos()
        {
            while (!this.IsDisposed)
            {
                var tmpDefinition = TVVS.QosInformation.QosDownResolutionData.Height.ToString();
                if (tmpDefinition != curDefinition)
                    CurDefinition = tmpDefinition;
                int netLag = TVVS.QosInformation.QosDownVideoLost + TVVS.QosInformation.QosDownAudioLost / 2;
                btn_NetState._Text = netLag <= 10 ? "网络较好" : netLag <= 40 ? "网络一般" : "网络较差";
                btn_NetState.NormalFgColor = netLag <= 10 ? Color.Green : netLag <= 40 ? Color.Yellow : Color.Red;
                await Task.Delay(1000);
            }
        }

        private async void DefinitionChanging(string preDf, object preTag, PictureButton pb, int timeout = 3000)
        {
            btn_Definition._Text = TVString.STR_Switching;
            await Task.Delay(3000);
            if (CurDefinition == (string)pb.Tag)
            {
                btn_Definition._Text = pb._Text;
                btn_Definition.Tag = Tag;
            }
            else
            {
                btn_Definition._Text = preDf;
                btn_Definition.Tag = preTag;
            }
            definitionChanging = false;
        }

        private async void SendText()
        {
            var txt = txt_MessageInput.Text.Trim();
            if (string.IsNullOrEmpty(txt)) return;
            txt_MessageInput.Enabled = false;
            TVVS.Features_SendText(txt);
            await Task.Delay(1000);
            txt_MessageInput.Text = string.Empty;
            txt_MessageInput.Enabled = true;
            txt_MessageInput.Focus();

            Label tmpLab = new Label();
            tmpLab.AutoSize = true;
            tmpLab.Text = txt;
            tmpLab.Font = TVFont.DefaultFont12;
            tmpLab.BackColor = TVColor.Color_Dark;
            tmpLab.ForeColor = TVColor.Color_White;
            tmpLab.Anchor = AnchorStyles.Left | AnchorStyles.Bottom;
            tmpLab.TextAlign = ContentAlignment.MiddleLeft;
            tmpLab.Padding = new Padding(5);
            tmpLab.Hide();
            panel_Remote.Controls.Add(tmpLab);
            TxtList.Add(tmpLab);
            for (int i = 0; i < TxtList.Count; i++)
            {
                Point point = new Point(10, TxtList[i].Parent.Height - (TxtList.Count - i) * (tmpLab.Height + 5));
                TxtList[i].Location = point;
                TxtList[i].Show();
            }
        }

        private async void ClearText()
        {
            btn_ClearTxt.Enabled = false;
            TVVS.Features_ClearText();
            await Task.Delay(1000);
            btn_ClearTxt.Enabled = true;
            TxtList.ForEach(o =>
            {
                o.Parent = null;
            });
            TxtList.Clear();
        }

        private void SetScreenModel()
        {
            if (IsFullScreen)
            {
                preParent = this.Parent;
                this.Hide();
                this.Parent = null;
                this.TopLevel = true;
                this.Show();
                this.WindowState = FormWindowState.Maximized;
                Windows_Main.Instance.Hide();
            }
            else
            {
                Windows_Main.Instance.Show();
                //this.Hide();
                this.Show();
                this.TopLevel = false;
                this.Dock = DockStyle.Fill;
                this.Parent = preParent;
                this.Size = Parent.Size;
            }
        }

        private void Panel_Remote_MouseDown(object sender, MouseEventArgs e)
        {
            if (isFocus)
            {
                DoFocus(e);
            }
        }

        private void DoFlash()
        {
            isFlash = !isFlash;
            btn_Flash.BackColor = isFlash ? TVColor.Color_HighLight : TVColor.Color_DarkDim;
            TVVS.Features_Flash();
        }

        private void DoZoom()
        {
            isZoom = !isZoom;
            btn_Zoom.BackColor = isZoom ? TVColor.Color_HighLight : TVColor.Color_DarkDim;
            if (isZoom)
            {
                ShowZoomBar();
            }
            else
            {
                HideZoomBar();
            }
        }

        private void ShowZoomBar()
        {
            Point newPoint = PointToClient(btn_Zoom.PointToScreen(Point.Empty));
            newPoint.X -= tvslider_Zoom.Width;
            newPoint.Y += (btn_Zoom.Height - tvslider_Zoom.Height) / 2;
            tvslider_Zoom.Location = newPoint;
            tvslider_Zoom.Show();
        }
        private void HideZoomBar()
        {
            tvslider_Zoom.Hide();
        }

        private void ShowGlassSettingBar()
        {
            Point newPos = PointToClient(btn_GlassSetting.PointToScreen(Point.Empty));
            newPos.X -= panel_GlassSetting.Width - btn_GlassSetting.Width;
            newPos.Y -= panel_GlassSetting.Height;
            panel_GlassSetting.Location = newPos;
            panel_GlassSetting.Show();
        }
        private void HideGlassSettingBar()
        {
            panel_GlassSetting.Hide();
        }

        private void ReadyFocus()
        {
            isFocus = true;
            btn_Focus.BackColor = isFocus ? TVColor.Color_HighLight : TVColor.Color_DarkDim;
            this.Cursor = Cursors.Cross;
        }
        private void DoFocus(MouseEventArgs e)
        {
            int width = panel_Remote.Width;
            int height = panel_Remote.Height;
            TVVS.Features_Focus(width, height, e.X, e.Y);
            this.Cursor = Cursors.Default;
            isFocus = false;
            btn_Focus.Checked = false;
        }

        private async void DoMark()
        {
            if (isMark)
            {
                CloseMark();
                return;
            }
            if (isSrcShot)
            {
                QuitSrcShot();
                await Task.Delay(200);
            }
            if (isPhoto)
            {
                QuitPhoto();
                await Task.Delay(200);
            }

            var target = panel_Remote;
            winDraw = new Windows_Draw(target);
            winDraw.Show(this);
            isMark = true;
        }

        private void CloseMark()
        {
            if (winDraw != null)
            {
                ((Windows_Draw)winDraw).ClearMark();
                winDraw.Hide();
                winDraw.Close();
            }
            btn_Mark.Checked = false;
            isMark = false;
        }

        private async void DoTakePhoto()
        {
            if (isPhoto)
            {
                QuitPhoto();
                return;
            }
            if (isMark)
            {
                CloseMark();
                await Task.Delay(200);
            }
            if (isSrcShot)
            {
                QuitSrcShot();
                await Task.Delay(200);
            }

            isPhoto = true;
            TVVS.Features_TakePhoto((o) =>
            {
                HttpAPI.DownloadDataCompleted += HttpAPI_DownloadDataCompleted;
                HttpAPI.GetAsync(new Uri(o), System.Net.HttpRequestHeader.Accept, HttpRequestHeaderValue.None);
            });

            Windows_MessageBox wmb = new Windows_MessageBox(TVString.STR_WattingForPhoto, MessageBoxButtons.OK, MessageBoxIcon.Information);
            wmb.BackColor = Color.FromArgb(30, 30, 30);
            wmb.SetConfirmText(TVString.STR_Cancel);
            wmb.BtnConfirm.NormalBgColor = TVColor.Color_DarkDim;
            wmb.BtnConfirm.NormalFgColor = TVColor.Color_White;
            wmb.BtnConfirm.HoverBgColor = Color.FromArgb(60, 60, 60);
            wmb.BtnConfirm.HoverFgColor = Color.White;
            wmb.LabMsg.ForeColor = TVColor.Color_White;
            HttpAPI.DownloadDataCompleted += (a, e) =>
            {
                if (wmb != null)
                    wmb.Close();
            };
            var ret = wmb.ShowDialog(this);
            if (ret == DialogResult.OK)
            {
                QuitPhoto();
            }
        }

        private void HttpAPI_DownloadDataCompleted(object sender, System.Net.DownloadDataCompletedEventArgs e)
        {
            if (!isPhoto) return;
            MemoryStream ms = new MemoryStream(e.Result);
            Image img = Image.FromStream(ms);
            winImgDraw = new Windows_ImageDraw(panel_Remote, img);
            winImgDraw.Show(this);
            HttpAPI.DownloadDataCompleted -= HttpAPI_DownloadDataCompleted;
        }

        public void QuitPhoto()
        {
            var opfs = Application.OpenForms.OfType<Windows_MessageBox>();
            opfs.ToList().ForEach(o => o.Close());
            if (winImgDraw != null)
            {
                winImgDraw.Hide();
                winImgDraw.Close();
                winImgDraw = null;
            }
            isPhoto = false;
            btn_TakePhoto.Checked = false;
            TVVS.Features_LeaveTakingPhoto();
            Windows_Main.Instance.Activate();
        }

        public async void DoScreenShot()
        {
            if (isSrcShot)
            {
                QuitSrcShot();
                return;
            }
            if (isMark)
            {
                CloseMark();
                await Task.Delay(200);
            }
            if (isPhoto)
            {
                QuitPhoto();
                await Task.Delay(200);
            }
            var img = GetPanelImage();
            winImgDraw = new Windows_ImageDraw(panel_Remote, img);
            winImgDraw.Show(this);
            isSrcShot = true;
        }
        public void QuitSrcShot()
        {
            if (winImgDraw != null)
            {
                winImgDraw.Hide();
                winImgDraw.Close();
                winImgDraw = null;
            }
            btn_ScreenShot.Checked = false;
            isSrcShot = false;
            TVVS.Features_LeaveTakingPhoto();
            Windows_Main.Instance.Activate();
        }
        private Image GetPanelImage()
        {
            //获取视频画面图片
            int width = panel_Remote.Width;     //获取宽度
            int height = panel_Remote.Height;     //获取高度
            const int SRCCOPY = 0xcc0020;     //复制图块的光栅操作码
            Bitmap sbmp = new Bitmap(width, height);     //用于保存图片的位图对象
            Graphics gSave = Graphics.FromImage(sbmp);     //创建该位图的Graphics对象
            HandleRef hDcSave = new HandleRef(null, gSave.GetHdc());     //得到句柄
            Graphics gSrc = panel_Remote.CreateGraphics();     //创建窗体的Graphics对象
            HandleRef hDcSrc = new HandleRef(null, gSrc.GetHdc());
            BitBlt(hDcSave, 0, 0, width, height, hDcSrc, 0, 0, SRCCOPY);
            gSrc.ReleaseHdc();
            gSave.ReleaseHdc();
            gSrc.Dispose();
            gSave.Dispose();
            return sbmp;
        }


        private void DoSendImage()
        {

        }

        private async void ActiveToolWithReady()
        {
            table_Tools.Enabled = false;
            while (TVVS.QosInformation.QosDownResolutionData.Height == -1 || TVVS.QosInformation.QosDownResolutionData.Height == 0)
            {
                await Task.Delay(100);
            }
            table_Tools.Enabled = true;
        }


        private void SetBrightness(int value)
        {
            int tmpInt = brightness;
            brightness += value;

            if (brightness >= 0 & brightness <= 100)
            {
                TVVS.Features_BrightnessModify(value);
            }
            else
            {
                brightness = tmpInt;
            }

            UpdateGlassBC();
        }
        private void SetContrast(int value)
        {
            int tmpInt = contrast;
            contrast += value;

            if (contrast >= 0 & contrast <= 100)
            {
                TVVS.Features_ContrastModify(value);
            }
            else
            {
                contrast = tmpInt;
            }

            UpdateGlassBC();
        }
        private void UpdateGlassBC()
        {
            lab_Brightness.Text = TVString.STR_Brightness + "(" + brightness + ")";
            lab_Contrast.Text = TVString.STR_Contrast + "(" + contrast + ")";
        }

        #endregion


        #region Win32 Api

        [DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
        public static extern int BitBlt(HandleRef hDC, int x, int y, int nWidth, int nHeight, HandleRef hSrcDC, int xSrc, int ySrc, int dwRop);

        #endregion

    }
}
